<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-03-02
 * Time: 15:40
 */

class http
{
    public $http = null;

    public function __construct($host, $port = 80)
    {
        $this->http = new swoole_http_client($host, $port);
        $this->http->set([
            'timeout' => 3.0, //Http请求超时检测。单位为秒，最小粒度支持毫秒。
            'keep_alive' => false, //启用或关闭Http长连接。默认开启，HTTP请求关闭，websocket打开
            'websocket_mask' => false //WebSocket客户端启用或关闭掩码。默认关闭。启用会对WebSocket客户端发送的数据使用掩码进行数据转换。
        ]);
    }

    /**
     * object(Swoole\Http\Client)#2 (20) {
    ["type"]=>
    int(1025)
    ["errCode"]=>
    int(0)
    ["statusCode"]=>
    int(200)
    ["host"]=>
    string(15) "www.laravel.com"
    ["port"]=>
    int(80)
    ["requestMethod"]=>
    NULL
    ["requestHeaders"]=>
    NULL
    ["requestBody"]=>
    NULL
    ["uploadFiles"]=>
    NULL
    ["set_cookie_headers"]=>
    array(1) {
    ["laravel_session"]=>
    string(369) "laravel_session"
    }
    ["downloadFile"]=>
    NULL
    ["headers"]=>
    array(8) {
    ["server"]=>
    string(12) "nginx/1.15.6"
    ["content-type"]=>
    string(16) "application/json"
    ["transfer-encoding"]=>
    string(7) "chunked"
    ["connection"]=>
    string(5) "close"
    ["x-powered-by"]=>
    string(10) "PHP/7.2.12"
    ["cache-control"]=>
    string(17) "no-cache, private"
    ["date"]=>
    string(29) "Sat, 02 Mar 2019 08:12:04 GMT"
    ["set-cookie"]=>
    string(369)"laravel_session"
    }
    ["cookies"]=>
    array(1) {
    ["laravel_session"]=>
    string(282) "eyJpdiI6IlwvSlwvUG44c1F\"
    }
    ["body"]=>
    string(24) "{"name":null,"age":null}"
    ["onConnect"]=>
    NULL
    ["onError"]=>
    NULL
    ["onMessage"]=>
    NULL
    ["onClose"]=>
    NULL
    ["setting"]=>
    array(3) {
    ["timeout"]=>
    float(3)
    ["keep_alive"]=>
    bool(false)
    ["websocket_mask"]=>
    bool(false)
    }
    ["sock"]=>
    int(5)
    }
     */
    public function getRequest($cgi)
    {
        $this->http->get($cgi, function ($cli) {
            var_dump($cli);
        });
        return '2222';
    }

    public function postRequest($cgi, $data)
    {
        $this->http->post($cgi, $data, function ($cli) {
            var_dump($cli);
        });
        return '2222';
    }

    public function requset($cgi, $method, $data)
    {
        $this->http->setMethod($method);
        $this->http->setData('age', $data['age']);
        $this->http->setData('name', $data['name']);
        $this->http->execute($cgi, function ($cli) {
            var_dump($cli);
        });
        return '22222';
    }
}

$http = new http('www.laravel.com');

//请求路径一定要在最前边加 / 返回会报400
$res = $http->postRequest('/swoole/getData', ['name' => 'zhangsan', 'age' => 20]);
//$res = $http->requset('/swoole/getData', 'post', ['name' => 'zhangsan', 'age' => 20]);